
package com.iplant.basic.controller.bms;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import com.iplant.base.po.EnumItem;
import com.iplant.base.po.excel.ExcelData;
import com.iplant.base.utils.excel.ExcelReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.iplant.base.controller.BaseController;
import com.iplant.base.po.Pagination;
import com.iplant.base.po.ServiceResult;
import com.iplant.base.utils.RetCode;
import com.iplant.base.utils.serializer.CloneTool;
import com.iplant.base.utils.general.StringUtils;
import com.iplant.basic.service.BMSService;
import com.iplant.basic.service.po.bms.BMSDepartment;
import com.iplant.basic.service.po.bms.BMSEmployee;
import com.iplant.basic.service.po.bms.BMSPosition;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api/Department")
public class DepartmentController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(DepartmentController.class);
    @Autowired
    BMSService wBMSService;

    @GetMapping("/AllDepartment")
    Object AllDepartment(HttpServletRequest request) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {

            BMSEmployee wLoginUser = GetSession(request);

            int wParentID = StringUtils.parseInt(request.getParameter("ParentID"), -1);
            int wType = StringUtils.parseInt(request.getParameter("Type"));
            String wName = StringUtils.parseString(request.getParameter("Name"));
            int wActive = StringUtils.parseInt(request.getParameter("Active"), -1);

            Pagination wPagination = GetPagination(request);

            ServiceResult<List<BMSDepartment>> wServerRst = wBMSService.BMS_QueryDepartmentList(wLoginUser, wParentID,
                    wName, wType, wActive, wPagination);

            if (StringUtils.isEmpty(wServerRst.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServerRst.getResult(), wPagination.getTotalPage());
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServerRst.getFaultCode(), wServerRst.getResult(), null);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    @GetMapping("/InfoDepartment")
    Object InfoDepartment(HttpServletRequest request) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {

            BMSEmployee wBMSEmployee = GetSession(request);

            int wID = StringUtils.parseInt(request.getParameter("ID"));

            String wCode = StringUtils.parseString(request.getParameter("Code"));

            ServiceResult<BMSDepartment> wServerRst = wBMSService.BMS_QueryDepartmentByID(wBMSEmployee, wID, wCode);

            if (StringUtils.isEmpty(wServerRst.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServerRst.getResult());
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServerRst.getFaultCode(), null, wServerRst.getResult());
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    @PostMapping("/UpdateDepartment")
    Object UpdateDepartment(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {

            BMSEmployee wBMSEmployee = GetSession(request);
            if (!wParam.containsKey("data")) {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
                return wResult;
            }

            BMSDepartment wBMSDepartment = CloneTool.Clone(wParam.get("data"), BMSDepartment.class);
            ServiceResult<Integer> wServerRst = new ServiceResult<Integer>();
            if (wBMSDepartment.getID() > 0) {
                wServerRst = wBMSService.BMS_SaveDepartment(wBMSEmployee, wBMSDepartment);
            } else {
                wServerRst = wBMSService.BMS_AddDepartment(wBMSEmployee, wBMSDepartment);
            }

            if (StringUtils.isEmpty(wServerRst.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wBMSDepartment);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServerRst.getFaultCode());
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;

    }

    @GetMapping("/AllPosition")
    Object AllPosition(HttpServletRequest request) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {

            BMSEmployee wLoginUser = GetSession(request);

            int wDepartmentID = StringUtils.parseInt(request.getParameter("DepartmentID"));
            String wName = StringUtils.parseString(request.getParameter("Name"));
            int wActive = StringUtils.parseInt(request.getParameter("Active"));

            Pagination wPagination = GetPagination(request);

            ServiceResult<List<BMSPosition>> wServerRst = wBMSService.BMS_QueryPositionList(wLoginUser, wDepartmentID,
                    wName, wActive, wPagination);

            if (StringUtils.isEmpty(wServerRst.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServerRst.getResult(), wPagination.getTotalPage());
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServerRst.getFaultCode(), wServerRst.getResult(), null);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    @GetMapping("/InfoPosition")
    Object InfoPosition(HttpServletRequest request) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {

            BMSEmployee wBMSEmployee = GetSession(request);

            int wID = StringUtils.parseInt(request.getParameter("ID"));

            String wCode = StringUtils.parseString(request.getParameter("Code"));
            ServiceResult<BMSPosition> wServerRst = wBMSService.BMS_QueryPositionByID(wBMSEmployee, wID, wCode);

            if (StringUtils.isEmpty(wServerRst.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServerRst.getResult());
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServerRst.getFaultCode(), null, wServerRst.getResult());
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    @PostMapping("/UpdatePosition")
    Object UpdatePosition(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {

            BMSEmployee wBMSEmployee = GetSession(request);

            if (!wParam.containsKey("data")) {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
                return wResult;
            }

            BMSPosition wBMSPosition = CloneTool.Clone(wParam.get("data"), BMSPosition.class);
            ServiceResult<Integer> wServerRst = new ServiceResult<Integer>();
            if (wBMSPosition.getID() > 0) {
                wServerRst = wBMSService.BMS_SavePosition(wBMSEmployee, wBMSPosition);
            } else {
                wServerRst = wBMSService.BMS_AddPosition(wBMSEmployee, wBMSPosition);
            }

            if (StringUtils.isEmpty(wServerRst.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wBMSPosition);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServerRst.getFaultCode());
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;

    }

    @PostMapping("/ActiveDepartment")
    Object ActiveDepartment(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {

            BMSEmployee wBMSEmployee = GetSession(request);

            if (!wParam.containsKey("data") || !wParam.containsKey("Active")) {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
                return wResult;
            }

            int wActive = StringUtils.parseInt(wParam.get("Active"));
            List<BMSDepartment> wBMSDepartmentList = CloneTool.CloneArray(wParam.get("data"), BMSDepartment.class);
            ServiceResult<Integer> wServerRst = new ServiceResult<Integer>();
            for (BMSDepartment wBMSDepartment : wBMSDepartmentList) {
                if (wActive == 1) {
                    wServerRst = wBMSService.BMS_ActiveDepartmentByID(wBMSEmployee, wBMSDepartment.getID());
                } else {
                    wServerRst = wBMSService.BMS_DisableDepartmentByID(wBMSEmployee, wBMSDepartment.getID());
                }
            }

            if (StringUtils.isEmpty(wServerRst.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServerRst.getResult());
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServerRst.getFaultCode(), null, wServerRst.getResult());
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    @PostMapping("/ActivePosition")
    Object ActivePosition(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {

            BMSEmployee wBMSEmployee = GetSession(request);

            if (!wParam.containsKey("data") || !wParam.containsKey("Active")) {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
                return wResult;
            }

            int wActive = StringUtils.parseInt(wParam.get("Active"));
            List<BMSPosition> wBMSPositionList = CloneTool.CloneArray(wParam.get("data"), BMSPosition.class);
            ServiceResult<Integer> wServerRst = new ServiceResult<Integer>();
            for (BMSPosition wBMSPosition : wBMSPositionList) {
                if (wActive == 1) {
                    wServerRst = wBMSService.BMS_ActivePositionByID(wBMSEmployee, wBMSPosition.getID());
                } else {
                    wServerRst = wBMSService.BMS_DisablePositionByID(wBMSEmployee, wBMSPosition.getID());
                }
            }
            if (StringUtils.isEmpty(wServerRst.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServerRst.getResult());
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServerRst.getFaultCode(), null, wServerRst.getResult());
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    @PostMapping("/DeleteDepartment")
    Object DeleteDepartment(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {

            BMSEmployee wBMSEmployee = GetSession(request);

            if (!wParam.containsKey("data")) {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
                return wResult;
            }

            List<BMSDepartment> wBMSDepartmentList = CloneTool.CloneArray(wParam.get("data"), BMSDepartment.class);
            ServiceResult<Integer> wServerRst = new ServiceResult<Integer>();
            for (BMSDepartment wBMSDepartment : wBMSDepartmentList) {
                if (wBMSDepartment == null || wBMSDepartment.Active != 0 || wBMSDepartment.ID <= 0) {
                    continue;
                }
                wServerRst = wBMSService.BMS_DeleteDepartment(wBMSEmployee, wBMSDepartment);
            }

            if (StringUtils.isEmpty(wServerRst.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServerRst.getResult());
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServerRst.getFaultCode(), null, wServerRst.getResult());
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    @PostMapping("/DeletePosition")
    Object DeletePosition(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {

            BMSEmployee wBMSEmployee = GetSession(request);

            if (!wParam.containsKey("data")) {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
                return wResult;
            }

            List<BMSPosition> wBMSPositionList = CloneTool.CloneArray(wParam.get("data"), BMSPosition.class);
            ServiceResult<Integer> wServerRst = new ServiceResult<Integer>();
            for (BMSPosition wBMSPosition : wBMSPositionList) {
                if (wBMSPosition == null || wBMSPosition.Active != 0 || wBMSPosition.ID <= 0) {
                    continue;
                }
                wServerRst = wBMSService.BMS_DeletePosition(wBMSEmployee, wBMSPosition);

            }
            if (StringUtils.isEmpty(wServerRst.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServerRst.getResult());
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServerRst.getFaultCode(), null, wServerRst.getResult());
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 获取部门类型列表
     */
    @GetMapping("/TypeList")
    public Object TypeList(HttpServletRequest request) {
        Object wResult = new Object();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            ServiceResult<List<EnumItem>> wServiceResult = wBMSService.BMS_QueryDepartmentTypeList(wLoginUser);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServiceResult.Result, null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 部门导入
     */
    @PostMapping("/Import")
    public Object Import(HttpServletRequest request, @RequestParam("file") MultipartFile[] files) {
        Object wResult = new Object();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            if (files.length == 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, "提示：没有要上传的Excel文件！");
            }

            ServiceResult<Integer> wServiceResult = new ServiceResult<>();
            ServiceResult<ExcelData> wExcelData = null;
            String wOriginalFileName = null;
            for (MultipartFile wMultipartFile : files) {
                wOriginalFileName = wMultipartFile.getOriginalFilename();

                assert wOriginalFileName != null;
                if (wOriginalFileName.contains("xlsx"))
                    wExcelData = ExcelReader.getInstance().readMultiSheetExcel(wMultipartFile.getInputStream(),
                            wOriginalFileName, "xlsx", 1000000);
                else if (wOriginalFileName.contains("xls"))
                    wExcelData = ExcelReader.getInstance().readMultiSheetExcel(wMultipartFile.getInputStream(),
                            wOriginalFileName, "xls", 1000000);

                assert wExcelData != null;
                if (StringUtils.isNotEmpty(wExcelData.FaultCode)) {
                    wResult = GetResult(RetCode.SERVER_CODE_ERR, wExcelData.FaultCode);
                    return wResult;
                }

                wServiceResult = wBMSService.BMS_ImportDepartment(wLoginUser, wExcelData.Result);

                if (!StringUtils.isEmpty(wServiceResult.FaultCode))
                    break;
            }

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "导入成功!", null, null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

}
